package com.xhs.controller;

import com.xhs.dto.request.ContentRequest;
import com.xhs.dto.response.ApiResponse;
import com.xhs.dto.response.ContentResponse;
import com.xhs.entity.Content;
import com.xhs.entity.User;
import com.xhs.security.UserPrincipal;
import com.xhs.service.ContentService;
import com.xhs.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 内容管理控制器
 */
@RestController
@RequestMapping("/contents")
@Slf4j
public class ContentController {
    
    @Autowired
    private ContentService contentService;
    
    @Autowired
    private UserService userService;
    
    /**
     * 发布内容
     */
    @PostMapping
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<ContentResponse>> createContent(
            @Valid @RequestPart("content") ContentRequest request,
            @RequestPart("file") MultipartFile file,
            Authentication authentication) {
        try {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            User user = userService.findById(userPrincipal.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            Content content = contentService.createContent(request, file, user);
            log.info("用户 {} 发布内容成功: {}", user.getUsername(), content.getTitle());
            
            return ResponseEntity.ok(ApiResponse.success("发布成功", ContentResponse.fromEntity(content)));
            
        } catch (Exception e) {
            log.error("发布内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("发布失败: " + e.getMessage()));
        }
    }
    
    /**
     * 修改内容
     */
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<ContentResponse>> updateContent(
            @PathVariable Long id,
            @Valid @RequestBody ContentRequest request,
            Authentication authentication) {
        try {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            User user = userService.findById(userPrincipal.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            Content content = contentService.updateContent(id, request, user);
            log.info("用户 {} 修改内容成功: {}", user.getUsername(), content.getTitle());
            
            return ResponseEntity.ok(ApiResponse.success("修改成功", ContentResponse.fromEntity(content)));
            
        } catch (Exception e) {
            log.error("修改内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("修改失败: " + e.getMessage()));
        }
    }
    
    /**
     * 删除内容
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<String>> deleteContent(
            @PathVariable Long id,
            Authentication authentication) {
        try {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            User user = userService.findById(userPrincipal.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            contentService.deleteContent(id, user);
            log.info("用户 {} 删除内容成功: {}", user.getUsername(), id);
            
            return ResponseEntity.ok(ApiResponse.success("删除成功"));
            
        } catch (Exception e) {
            log.error("删除内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("删除失败: " + e.getMessage()));
        }
    }
    
    /**
     * 查看内容详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<ContentResponse>> getContent(
            @PathVariable Long id,
            Authentication authentication) {
        try {
            Optional<Content> contentOpt = contentService.getContentById(id);
            if (!contentOpt.isPresent()) {
                return ResponseEntity.notFound().build();
            }
            
            Content content = contentOpt.get();
            
            // 记录访问
            User user = null;
            if (authentication != null) {
                UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
                user = userService.findById(userPrincipal.getId()).orElse(null);
            }
            contentService.recordView(id, user);
            
            return ResponseEntity.ok(ApiResponse.success(ContentResponse.fromEntity(content)));
            
        } catch (Exception e) {
            log.error("获取内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取内容失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取推荐内容
     */
    @GetMapping("/recommend")
    public ResponseEntity<ApiResponse<Page<ContentResponse>>> getRecommendedContents(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            User user = null;
            if (authentication != null) {
                UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
                user = userService.findById(userPrincipal.getId()).orElse(null);
            }
            
            Page<Content> contents = contentService.getRecommendedContents(user, page, size);
            Page<ContentResponse> contentResponses = contents.map(ContentResponse::fromEntity);
            return ResponseEntity.ok(ApiResponse.success(contentResponses));
            
        } catch (Exception e) {
            log.error("获取推荐内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取推荐内容失败: " + e.getMessage()));
        }
    }
    
    /**
     * 搜索内容
     */
    @GetMapping("/search")
    public ResponseEntity<ApiResponse<Page<ContentResponse>>> searchContents(
            @RequestParam String keyword,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            Page<Content> contents = contentService.searchContents(keyword, page, size);
            Page<ContentResponse> contentResponses = contents.map(ContentResponse::fromEntity);
            return ResponseEntity.ok(ApiResponse.success(contentResponses));
            
        } catch (Exception e) {
            log.error("搜索内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("搜索失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取我的内容
     */
    @GetMapping("/my")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<ApiResponse<Page<ContentResponse>>> getMyContents(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            Authentication authentication) {
        try {
            UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
            User user = userService.findById(userPrincipal.getId())
                    .orElseThrow(() -> new RuntimeException("用户不存在"));
            
            Page<Content> contents = contentService.getUserContents(user, page, size);
            Page<ContentResponse> contentResponses = contents.map(ContentResponse::fromEntity);
            return ResponseEntity.ok(ApiResponse.success(contentResponses));
            
        } catch (Exception e) {
            log.error("获取我的内容失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取内容失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取内容导航（上一个/下一个）
     */
    @GetMapping("/{id}/navigation")
    public ResponseEntity<ApiResponse<Map<String, ContentResponse>>> getContentNavigation(@PathVariable Long id) {
        try {
            Map<String, ContentResponse> navigation = new HashMap<>();
            
            Optional<Content> previous = contentService.getPreviousContent(id);
            Optional<Content> next = contentService.getNextContent(id);
            
            previous.ifPresent(content -> navigation.put("previous", ContentResponse.fromEntity(content)));
            next.ifPresent(content -> navigation.put("next", ContentResponse.fromEntity(content)));
            
            return ResponseEntity.ok(ApiResponse.success(navigation));
            
        } catch (Exception e) {
            log.error("获取内容导航失败: {}", e.getMessage());
            return ResponseEntity.badRequest()
                    .body(ApiResponse.error("获取导航失败: " + e.getMessage()));
        }
    }
} 